package com.algo.smartgwt.server.datas.course;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.algo.smartgwt.server.db.Country;
import com.algo.smartgwt.server.db.DBF;
import com.google.gson.Gson;
import com.googlecode.objectify.Objectify;

@Deprecated
public class New extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8123933216213522889L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//super.doGet(req, resp);
		doHandleRequest(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// super.doPost(req, resp);
		doHandleRequest(req, resp);
	}
	
	
	private Country storeCountry(Country cntr){
		//ObjectifyService.register(Country.class);
		
		Objectify ofy = DBF.getObjectify();

		// Simple create
		Country c = cntr;//new Country("a", "a", "a");
		ofy.put(c);
		//ofy.
		assert c.getId() != null;    // id was autogenerated
		
		log.log(Level.WARNING, "porsche.getId() == " + c.getId());
		
		return c;
		
	}

	private void doHandleRequest(HttpServletRequest req,
			HttpServletResponse resp) throws IOException {
		//Logger log = Logger.getLogger(Add.class.getName());
		log.log(Level.WARNING, req.toString());
		
		//Enumeration en = req.getAttributeNames();
		String s = "";
		
		BufferedReader rdr = req.getReader();
		
		String  s0;
		do {
			s0 = rdr.readLine(); 
			s += (s0==null?"":s0);
		} while ( s0 != null);
		
		Country cntr0 = null ;//DBF.testDeJSON(s, new Country());

		resp.setContentType("text/plain");
		
		Country cntr = storeCountry(cntr0);
		
		Gson gson = new Gson();
		
		Object rpl = DBF.prepareJSONReply(cntr);
		log.log(Level.WARNING, gson.toJson( rpl ));
		resp.getWriter().println(gson.toJson( rpl ));		
		
	}
	
	private static Logger log = Logger.getLogger(Add.class.getName()); 
	
}
